using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using QiHe.CodeLib;
using QiHe.Office.CompoundDocumentFormat;
using QiHe.Office.Excel;

namespace QiHe.Office.Tool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        CompoundDocument doc;
        private void openOToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string file = FileSelector.BrowseFile(FileType.All);
                if (file == null) return;
                doc = CompoundDocument.Read(file);
                treeViewDoc.Nodes.Clear();
                TreeNode root = treeViewDoc.Nodes.Add(Path.GetFileName(file));
                root.Nodes.Add("Header");
                AddTreeNode(root, doc.RootStorage);
                treeViewDoc.ExpandAll();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        void AddTreeNode(TreeNode node, DirectoryEntry entry)
        {
            TreeNode subnode = node.Nodes.Add(entry.Name);
            subnode.Tag = entry;
            foreach (KeyValuePair<string, DirectoryEntry> subentry in entry.Members)
            {
                AddTreeNode(subnode, subentry.Value);
            }
        }

        private void treeViewDoc_AfterSelect(object sender, TreeViewEventArgs e)
        {
            DirectoryEntry entry = e.Node.Tag as DirectoryEntry;
            if (entry != null)
            {
                if (entry.EntryType == EntryType.Stream)
                {
                    byte[] data = entry.Data;

                    textBoxHexView.Text = Bin2Hex.Format(data);
                    textBoxShowText.Text = Encoding.Unicode.GetString(data);
                }
            }
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            if (doc == null) return;
            if (e.TabPage == tabPageExcell)
            {
                //try
                {
                    LoadExcelSheets();
                }
                //catch (Exception error)
                //{
                //    MessageBox.Show(error.Message);
                //}
            }
        }

        private void LoadExcelSheets()
        {
            byte[] bookdata = doc.GetStreamData("Workbook");
            Workbook book = new Workbook();
            book.Read(new MemoryStream(bookdata));

            //ExtractImages(book, @"C:\Images");

            tabControlSheets.TabPages.Clear();

            foreach (Worksheet sheet in book.Worksheets)
            {
                TabPage sheetPage = new TabPage(sheet.Name);
                DataGridView dgvCells = new DataGridView();
                dgvCells.Dock = DockStyle.Fill;
                dgvCells.RowCount = sheet.MaxRowIndex + 1;
                dgvCells.ColumnCount = sheet.MaxColIndex + 1;

                foreach (KeyValuePair<Pair<int, int>, Cell> cell in sheet.Cells)
                {
                    dgvCells[cell.Key.Right, cell.Key.Left].Value = cell.Value.Value;
                    if (cell.Value.BackColorIndex != 64)
                    {
                        dgvCells[cell.Key.Right, cell.Key.Left].Style.BackColor = cell.Value.BackColor;
                    }
                }

                foreach (KeyValuePair<Pair<int, int>, Picture> cell in sheet.Pictures)
                {
                    int rowIndex = cell.Key.Left;
                    int colIndex = cell.Key.Right;
                    if (dgvCells.RowCount < rowIndex + 1)
                    {
                        dgvCells.RowCount = rowIndex + 1;
                    }
                    if (dgvCells.ColumnCount < colIndex + 1)
                    {
                        dgvCells.ColumnCount = colIndex + 1;
                    }
                    dgvCells[colIndex, rowIndex].Value = String.Format("<Image,{0}>", cell.Value.ImageData.Length);
                }

                sheetPage.Controls.Add(dgvCells);
                tabControlSheets.TabPages.Add(sheetPage);
            }
        }

        void ExtractImages(Workbook book, string path)
        {
            if (book.DrawingGroup == null) return;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            Worksheet sheet1 = book.Worksheets[0];
            foreach (KeyValuePair<Pair<int, int>, Picture> pic in sheet1.Pictures)
            {
                string filename = String.Format("image{0}-{1}", pic.Key.Left, pic.Key.Right)
                    + GetImageFileExtension(pic.Value.ImageFormat);
                string file = Path.Combine(path, filename);
                File.WriteAllBytes(file, pic.Value.ImageData);
            }
        }

        static string GetImageFileExtension(ushort imagetype)
        {
            switch (imagetype)
            {
                case EscherRecordType.MsofbtBlipBitmapJPEG:
                    return ".jpeg";
                case EscherRecordType.MsofbtBlipBitmapPNG:
                    return ".png";
                case EscherRecordType.MsofbtBlipBitmapDIB:
                    return ".bmp";
                case EscherRecordType.MsofbtBlipBitmapPS:
                    return ".psd";
                default:
                    return null;
            }
        }

        private void exitXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}